package com.ww.web;

import com.alibaba.fastjson.JSON;
import com.ww.dao.NewsDao;
import com.ww.dao.UserDao;
import com.ww.dao.impl.NewsDaoImpl;
import com.ww.entity.News;
import com.ww.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebServlet("/news/*")
public class NewsServlet extends HttpServlet {
    private NewsDao newsDao=new NewsDaoImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String baseURL = req.getContextPath();//获取项目的基本路径
        String uri = req.getRequestURI();
        String path = uri.substring(uri.lastIndexOf("/") + 1);
        if ("index_list.do".equals(path)){
            List<News> newsList = newsDao.findPage(1, 3);
            resp.setContentType("application/json;charset=utf-8");
            String json = JSON.toJSONString(newsList);
            PrintWriter out = resp.getWriter();
            out.write(json);
            out.close();
            return;
        }else if ("list.do".equals(path)){
            List<News> newsList = newsDao.findnums();
            req.setAttribute("newsList",newsList);
            req.getRequestDispatcher(baseURL+"/news.jsp").forward(req,resp);
        }else if ("list_detail.do".equals(path)){
            String newsId = req.getParameter("newsId");
            News news = newsDao.findById(newsId);
            req.setAttribute("news", news);
            req.getRequestDispatcher(baseURL + "/newsdetail.jsp").forward(req, resp);
            return;
        }else if ("list_nums.do".equals(path)){
            String news_id = req.getParameter("news_id");
            int nums = newsDao.increaseReadNums(news_id);
            resp.setContentType("application/json;charset=utf-8");
            PrintWriter out = resp.getWriter();
            out.write("success");
            out.close();
            return;
        }else {
            throw new RuntimeException("请求错误");
        }
    }
}
